package com.dc.boot.autoconfigure.swagger2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


/*******************************************************************************
 * 文件名: Swagger2AutoConfiguration.java.java <br>
 * 版本: <br>
 * 描述: Swagger2 自动装配   <br>
 *      默认启用 可以设置 spring.swagger2.enabled=false 禁用
 * 版权所有:神州数码<br>
 * //////////////////////////////////////////////////////// <br>
 * 创建者: 王建栋 <br>
 * 创建日期: 2017年8月4日 <br>
 * 修改者: <br>
 * 修改日期: <br>
 * 修改说明: <br>
 ******************************************************************************/
@Configuration
@EnableSwagger2
@EnableConfigurationProperties(Swagger2Properties.class)
@ConditionalOnProperty(prefix = "spring.swagger2", name = "enabled", matchIfMissing = true)
public class Swagger2AutoConfiguration {

	@Autowired
	private Swagger2Properties swagger2Properties;
	
	@Bean
    public Docket defaultRestApi() {
        ApiSelectorBuilder builder= new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select();
        if(StringUtils.hasLength(swagger2Properties.getPackages())){
        	builder.apis(RequestHandlerSelectors.basePackage(swagger2Properties.getPackages()));
        }
        
        if(StringUtils.hasLength(swagger2Properties.getAnt())){
        	builder.paths(PathSelectors.ant(swagger2Properties.getAnt()));
        }else if(StringUtils.hasLength(swagger2Properties.getRegex())){
        	builder.paths(PathSelectors.regex(swagger2Properties.getRegex()));
        }else{
        	builder.paths(PathSelectors.any());
        }
        return builder.build();
    }

    private ApiInfo apiInfo() {
       return   new ApiInfoBuilder()
	                .title(swagger2Properties.getTitle())
	                .description(swagger2Properties.getDescription())
	                .contact(swagger2Properties.getContact())
	                .termsOfServiceUrl(swagger2Properties.getTermsOfServiceUrl())
	                .license(swagger2Properties.getLicense())
	                .licenseUrl(swagger2Properties.getLicenseUrl())
	                .version(swagger2Properties.getVersion())
	                .build();
    }
}

